<?php /** @noinspection ALL */

/**
 * @link https://www.len168.com
 * @copyright Copyright (c) 19-1-12 len168.com
 * @author toshcn <toshcn@foxmail.com>
 */

namespace api\controllers;

use Yii;
use yii\helpers\ArrayHelper;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use common\models\InviteRegisterForm;
use common\models\LoginForm;
use common\models\Payin;
use common\models\RegisterForm;
use common\models\SmsCaptchaForm;
use common\models\User;

/**
 * 账户 接口
 * Class AccountController
 * @package api\modules\v1\controllers
 * @author toshcn <toshcn@foxmail.com>
 */
class AccountController extends BaseController
{
    /**
     * 获取第三方appid
     * @return mixed
     */
    public function actionOauthAppid()
    {
        $alipay = Yii::$app->config->getSiteItem('alipayOauth');
        return Yii::$app->api->success(['alipayAppId' => isset($alipay['appId']) ? $alipay['appId'] : '']);
    }

    /**
     * 第三方登录 code授权方式 需要到第三方平台换token
     * @return mixed
     * @throws \Throwable
     */
    public function actionOauthLogin()
    {
        $this->validateIsPost();
        $code = trim(Yii::$app->getRequest()->post('code'));
        $type = trim(Yii::$app->getRequest()->post('type'));
        $oauth = Yii::$app->oauth;
        if ($type == 'alipay') {
            $oauth->oauthHandler = $oauth::ALIPAY;
        } else if ($type == 'weixin') {
            $oauth->oauthHandler = $oauth::WEIXIN;
        }
        $data = $oauth->getToken($code);
        if ($data['status'] == 1) {
            $model = new LoginForm(['scenario' => 'oauth_login']);
            $model->unionid = $data['data']['account'];
            $model->type = $type;
            if ($model->validate() && $model->oauthLogin()) {
                // 登录成功返回用户资料
                return Yii::$app->api->success($model->rebackUserInfo());
            } else if ($model->hasErrors()) {
                return Yii::$app->api->error($model->getFirstErrorMessage());
            }
            return Yii::$app->api->error('登录失败');
        }

        return Yii::$app->api->error('授权失败');
    }

    /**
     * 第三方登录授权链接
     * @return mixed
     * @throws \Throwable
     */
    public function actionOauthUrl()
    {
        $this->validateIsPost();
        $type = trim(Yii::$app->getRequest()->post('type'));
        $oauth = Yii::$app->oauth;
        if ($type == 'alipay') {
            $oauth->oauthHandler = $oauth::ALIPAY;
            return Yii::$app->api->success(['url' => $oauth->createOauthUrl()]);
        }
        return Yii::$app->api->error('登录方式不支持');
    }

    /**
     * 第三方登录授权信息
     * @return mixed
     * @throws \Throwable
     */
    public function actionOauthInfo()
    {
        $this->validateIsPost();
        $type = trim(Yii::$app->getRequest()->post('type'));
        $oauth = Yii::$app->oauth;
        if ($type == 'alipay') {
            $oauth->oauthHandler = $oauth::ALIPAY;
            return Yii::$app->api->success(['authInfo' => $oauth->createOauthInfo()]);
        }
        return Yii::$app->api->error('登录方式不支持');
    }


    /**
     * 用户登录
     * @return mixed
     * @throws \Throwable
     */
    public function actionLogin()
    {
        $this->validateIsPost();
        $model = new LoginForm(['scenario' => Yii::$app->getRequest()->post('type') . '_login']);
        $model->load(Yii::$app->getRequest()->post(), '');
        if ($model->login()) {
            // 登录成功返回用户资料
            return Yii::$app->api->success($model->rebackUserInfo());
        } else if ($model->hasErrors()) {
            return Yii::$app->api->error($model->getFirstErrorMessage());
        }
        return Yii::$app->api->error('登录失败');
    }

    /**
     * 注册
     * @return mixed
     * @throws \yii\base\Exception
     */
    public function actionRegister()
    {
        $this->validateIsPost();
        $model = new RegisterForm();
        $model->load(Yii::$app->getRequest()->post(), '');
        if ($model->validate() && $model->register()) {
            return Yii::$app->api->success();
        } else if ($model->hasErrors()) {
            return Yii::$app->api->error($model->getFirstErrorMessage());
        }
        return Yii::$app->api->error('注册失败');
    }
    /**
     * 邀请注册
     * @return mixed
     * @throws \yii\base\Exception
     */
    public function actionInviteRegister()
    {
        $this->validateIsPost();
        $model = new InviteRegisterForm();
        $model->type = (int) Yii::$app->getRequest()->post('type');
        $model->load(Yii::$app->getRequest()->post(), '');
        $model->parent = 0;
        if ($model->register()) {
            return Yii::$app->api->success();
        }
        if ($model->hasErrors()) {
            return Yii::$app->api->error($model->getFirstErrorMessage());
        }
        return Yii::$app->api->error('注册失败');
    }

    /**
     * 邀请 检测邀请码时间
     * @return mixed
     * @throws \yii\base\Exception
     */
    public function actionInvite()
    {
        $this->validateIsPost();
        $code = Yii::$app->getRequest()->post('code');
        $out = 1;//邀请链接过期
        $data = [];
        if ($code && ($code = User::decodeInviteCode($code))) {
            $code = explode('_', $code);
            if ($urlDay = (int)Yii::$app->config->getUserItem('inviteRegisterUrlInterval')) {
                if (time() > strtotime("+{$urlDay} day", (int)$code[2])) {
                    $out = 1;
                } else {
                    $out = 0;
                }
            }
            if ($out == 0 && ($user = User::findOne($code[1]))) {
                $data = $user->inviteUserInfo();
            }
        }
        return Yii::$app->api->success(['codeIsOut' => $out, 'userInfo' => $data]);
    }
}
